package com.soft.line.util.encrypt;

import cn.hutool.crypto.symmetric.SymmetricCrypto;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author 86185
 * @date 2020/5/9 16:49
 */
@Slf4j
public class BaseEncrypt {

    private static final int DEFAULT_KEY_LENGTH = 16;
    protected static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

    protected static String encrypt(SymmetricCrypto crypto, String content) {
        try {
            byte[] encrypt = crypto.encrypt(content);
            return Base64.encodeBase64String(encrypt);
        } catch (Exception e) {
            log.warn("encrypt error", e);
            throw new RuntimeException("encrypt content error.");
        }
    }

    protected static String decrypt(SymmetricCrypto crypto, String encrypt) {
        try {
            byte[] contentByte = Base64.decodeBase64(encrypt);
            byte[] decrypt = crypto.decrypt(contentByte);
            return new String(decrypt);
        } catch (Exception e) {
            log.warn("decrypt error", e);
            throw new RuntimeException("decrypt error.");
        }
    }

    protected static byte[] concat(byte[] key) {
        return concat(key, DEFAULT_KEY_LENGTH);
    }

    protected static byte[] concat(byte[] key, int keyLength) {
        if (key == null || key.length == keyLength) {
            return key;
        }
        byte[] bytes = new byte[keyLength];
        if (key.length > keyLength) {
            System.arraycopy(key, 0, bytes, 0, keyLength);
        } else {
            int len = keyLength - key.length;
            for (int i = 0; i < len; i++) {
                byte[] b = {(byte) len};
                key = concat(key, b);
            }
            bytes = key;
        }
        return bytes;
    }

    private static byte[] concat(byte[] firstArray, byte[] secondArray) {
        if (firstArray == null || secondArray == null) {
            return null;
        }
        byte[] bytes = new byte[firstArray.length + secondArray.length];
        System.arraycopy(firstArray, 0, bytes, 0, firstArray.length);
        System.arraycopy(secondArray, 0, bytes, firstArray.length, secondArray.length);
        return bytes;
    }

}
